import gobject
import numpy as np
import matplotlib
matplotlib.use('GTKAgg')

import matplotlib.pyplot as plt

from octopus import *

PIN		    = 38
INTERVALL_IN_MS	    = 100
INTERVALLE_X_ACHSE  = 500
MAXIMUM_Y	    = 6
BESCHRIFTUNG	    = "Spannung V Pin " + str(PIN)

def umrechnung(adwert):
    'umrechung fuer adwert in physikalische Groesse'

    return (5.0/1024)*adwert # 5V Referenzspannung durch AD-Aufloesung mal AD-Wert

# ab hier kommt das Programm

samples = []
samples_index = 0

for i in range(INTERVALLE_X_ACHSE):
  samples.append(0)

fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot(samples)
ax.set_ylim(0, MAXIMUM_Y)
ax.legend( (BESCHRIFTUNG,) )


op=octopus_context()
octopus_init(op)
octopus_open(op)
octopus_adc_init(op, PIN)
octopus_adc_ref(op, 2)



def ad_new_value(pin):
    global op

    value = octopus_adc_get(op, PIN)
    print value
    return value

def update():
    global samples_index
    line.set_ydata(samples)
    fig.canvas.draw_idle()
    samples[samples_index] = umrechnung(ad_new_value(PIN))

    samples_index += 1

    if samples_index > INTERVALLE_X_ACHSE-1:
      samples_index = 0

    return True  # return False to terminate the updates

gobject.timeout_add(INTERVALL_IN_MS, update) 
plt.show()
